﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Web;

namespace EnterpriseFund.BLL
{
   public class QueryAllowanceForecast
    {
       private readonly DAL.QueryAllowanceForecast dal = new DAL.QueryAllowanceForecast();

       /// <summary>
       /// 取年度企业可补贴税种税款汇总信息
       /// </summary>
       public DataTable GetTaxClassAllowanceTotal(decimal year,decimal nsrdzdah = 0)
       {          
            var procedureName = "fund.sp_GetTaxClassAllowanceTotalByYear";
            var parameterYear = new SqlParameter("year", year);
            var parameterNsrdzdah = new SqlParameter("nsrdzdah", nsrdzdah);
            var parameters = new SqlParameter[] { parameterYear, parameterNsrdzdah };
            var taxs = dal.RunProcedure(procedureName, parameters);
            return taxs;
       }

       //取某企业可补贴数据（缓存一分钟)
       private DataTable GetAllowanceTotalByNsrdzdah(decimal year,decimal nsrdzdah)
       {
               var cacheKey = "AllowanceTotal" + year + nsrdzdah;
               var tax = HttpRuntime.Cache[cacheKey];
               if (tax == null)
               {
                   tax = GetTaxClassAllowanceTotal(year,nsrdzdah);
                   HttpRuntime.Cache.Insert(cacheKey, tax, null, DateTime.MaxValue, TimeSpan.FromMinutes(1));
               }
               return tax as DataTable;
       }

       /// <summary>
       /// 按年度获取企业可补贴税金额的预测数据
       /// </summary>
       /// <param name="year">年份</param>
       /// <param name="nsrdzdah">纳税人电子档案号</param>
       /// <returns></returns>
        public DataTable GetAllowanceForecast(decimal year)
        {
            var taxs = GetTaxClassAllowanceTotal(year);

            //设置主键
            taxs.PrimaryKey = new DataColumn[] { taxs.Columns["NSRDZDAH"] };

            //添加相应政策列与可补贴金额列
            var taxClassAllowance = new BLL.TaxClassAllowance().GetModelList("FYear = " + year);
            foreach(var tc in taxClassAllowance)
            {  
                var ruleFormulaColumn = new DataColumn("FRuleFormula_" + tc.FTaxClassAllowanceNo,System.Type.GetType("System.String"));
                taxs.Columns.Add(ruleFormulaColumn);

                var computeValueColumn = new DataColumn("FComputeValue_" + tc.FTaxClassAllowanceNo,System.Type.GetType("System.Decimal"));
                taxs.Columns.Add(computeValueColumn);

                var computeExpressionColumn = new DataColumn("FComputeExpression_" + tc.FTaxClassAllowanceNo);
                taxs.Columns.Add(computeExpressionColumn);               
            }
            //开始计算
            var sp = new SupportPolicy().GetFormatExpression(year);
            foreach (var p in sp)
            {
                var filter = string.Format("FEnterprisePropNo = '{0}' and {1}", p.FEnterprisePropNo, p.FRuleExpression);
                var taxList = taxs.Select(filter);
                foreach (var t in taxList)
                {
                    t["FRuleFormula_" + p.FTaxClassAllowanceNo] = p.FRuleFormula;
                    t["FComputeExpression_" + p.FTaxClassAllowanceNo] = p.FComputeExpression.Replace("[base]", "").Replace("[se]", t[p.FTaxClassAllowanceNo].ToString());
                }
            }

            return taxs;
        }

       /// <summary>
       /// 按年度获取企业可补贴税金额的预测数据
       /// 该方法在原方法的基础上实现了列转行
       /// </summary>
        public DataTable GetAllowanceForecast2(decimal year)
        {
            var taxs = GetTaxClassAllowanceTotal(year);

            //克隆一个新表
            var newTaxs = taxs.Clone();
            //为新表添加列
            var taxClassAllowanceNoColumn = new DataColumn("FTaxClassAllowanceNo");
            newTaxs.Columns.Add(taxClassAllowanceNoColumn);

            var taxClassAllowanceNameColumn = new DataColumn("FTaxClassAllowanceName");
            newTaxs.Columns.Add(taxClassAllowanceNameColumn);

            var seColumn = new DataColumn("se", System.Type.GetType("System.Decimal"));
            newTaxs.Columns.Add(seColumn);

            
            //为新表添加行
            var taxClassAllowance = new BLL.TaxClassAllowance().GetModelList("FYear = " + year);
            foreach (DataRow r in taxs.Rows)
            {
                foreach (var tc in taxClassAllowance)
                {
                    var values = r.ItemArray.ToList();
                    var se = (decimal)r[tc.FTaxClassAllowanceNo];
                    if (se != 0)
                    {
                        values.Add(tc.FTaxClassAllowanceNo);
                        values.Add(tc.FTaxClassAllowanceName);
                        values.Add(se);
                        newTaxs.Rows.Add(values.ToArray());
                    }
                }
            }
            taxs.Clear();
            taxs = null;
            //至此完成列转行,清除原数据表。
            //再添加列
            var ruleFormulaColumn = new DataColumn("FRuleFormula");
            newTaxs.Columns.Add(ruleFormulaColumn);

            var computeFormulaColumn = new DataColumn("FComputeFormula");
            newTaxs.Columns.Add(computeFormulaColumn);

            var computeValueColumn = new DataColumn("FComputeValue", System.Type.GetType("System.Decimal"));
            newTaxs.Columns.Add(computeValueColumn);

            //用于计算数据表。
            var computeTable = newTaxs.Clone();
            //开始按匹配新表数据
            var sp = new SupportPolicy().GetFormatExpression(year);
            //找到营改增税种编号
            var YGZAllowance = taxClassAllowance.SingleOrDefault(t => t.FTaxClassAllowanceName.IndexOf("营改增") >= 0);
            var YGZAllowanceNo = YGZAllowance != null ? YGZAllowance.FTaxClassAllowanceNo : "";
            
            foreach (var p in sp)
            {
                //如果当前是营改增税种，则计算时须先减去营改增补助金额
                if (p.FTaxClassAllowanceNo == YGZAllowanceNo)
                {
                    p.FComputeExpression = p.FComputeExpression.Replace("[se]", "([se] - [FAmount])");
                }
                var filter = string.Format("FEnterprisePropNo = '{0}' and FTaxClassAllowanceNo = '{1}' and {2}", p.FEnterprisePropNo,p.FTaxClassAllowanceNo, p.FRuleExpression);
                
                var taxList = new DataRow[0];
                try//
                {
                    taxList = newTaxs.Select(filter);
                }
                catch
                { 
                    //
                }
                if (taxList.Length > 0)
                {
                    computeTable.Columns["FComputeValue"].Expression = p.FComputeExpression;
                
                    foreach (var t in taxList)
                    {
                        //如需要基数，在此获取。
                        if (p.IsEvalBase)
                        {
                            var lastYearTotal = GetAllowanceTotalByNsrdzdah(year - 1, (decimal)t["NSRDZDAH"]);
                            if (lastYearTotal.Rows.Count == 1)
                            {
                                t["base"] = lastYearTotal.Rows[0][p.FTaxClassAllowanceNo];
                            }

                        }

                        computeTable.Rows.Add(t.ItemArray);

                        t["FRuleFormula"] = p.FRuleFormula;
                        t["FComputeFormula"] = p.FComputeFormula;
                        t["FComputeValue"] = Math.Round((decimal)computeTable.Rows[0]["FComputeValue"],2);

                        computeTable.Clear();
                    }
                }
            }
            return newTaxs;
        }

    }
}
